package cuiyt.juc.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cyt
 * @create 2020-04-29 20:55
 */
// cuiyt.juc 来解决问题
public class demo03 {
    public static void main(String[] args) {
        data3 data3 = new data3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data3.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data3.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data3.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data3.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

class data3 {
    private Integer number = 0;
    // 创建一个锁
    Lock lock = new ReentrantLock();
    // 创建一个  Condition 对象来绑定到一个锁上面
    Condition condition = lock.newCondition();


    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
                // 等待
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "->" + number);
            // 通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public void decrement() throws InterruptedException {

        lock.lock();

        try {
            while (number == 0) {
                condition.await();
                // 等待
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "->" + number);
            // 通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
